﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace OLMS_MVC2.BLL
{
    public class ValidateCodeService
    {
        public (byte[] imageBytes, string code) GenerateValidateCode()
        {
            // 颜色数组
            Color[] colors = new Color[]
            {
                Color.Red, Color.Green, Color.Yellow, Color.Blue,
                Color.AliceBlue, Color.Aqua, Color.Bisque, Color.Brown
            };

            // 创建图片对象
            using (Image img = new Bitmap(100, 36))
            using (Graphics graphics = Graphics.FromImage(img))
            {
                Random random = new Random(DateTime.Now.Millisecond);

                // 生成4个随机字母
                string validCode = GenerateRandomLetters(random, 4);

                // 绘制验证码
                DrawLetters(graphics, random, colors, validCode);

                // 转换为字节数组
                using (MemoryStream ms = new MemoryStream())
                {
                    img.Save(ms, ImageFormat.Jpeg);
                    return (ms.ToArray(), validCode);
                }
            }
        }

        private string GenerateRandomLetters(Random random, int count)
        {
            char[] letters = new char[count];
            for (int i = 0; i < count; i++)
            {
                letters[i] = (char)random.Next(97, 122); // a-z
            }
            return new string(letters);
        }

        private void DrawLetters(Graphics graphics, Random random, Color[] colors, string code)
        {
            Font font = new Font("宋体", 24);
            int[] yOffsets = { -3, -9, 0, -7 }; // Y轴偏移量

            for (int i = 0; i < code.Length; i++)
            {
                int x = 7 + i * 20; // X坐标计算
                graphics.DrawString(
                    code[i].ToString(),
                    font,
                    new SolidBrush(colors[random.Next(0, colors.Length)]),
                    x,
                    yOffsets[i]);
            }
        }
    }
}